package com.batch_demo.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {

    private static HttpClient getHttpsClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain,
                                     String authType) throws CertificateException {
                return true;
            }
        }).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
        HttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        return httpclient;
    }

    public static Document postHtml(String url, Map<String, String> map, Map<String, String> headerMap) {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
//            httpPost.setEntity(new UrlEncodedFormEntity(params, Charset.forName("utf-8")));
//            for (Map.Entry<String, String> entry : map.entrySet()) {
//                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
//            }

            httpPost.setEntity(new StringEntity(JSON.toJSONString(map)));
            for (Map.Entry<String, String> header : headerMap.entrySet()) {
                httpPost.addHeader(header.getKey(), header.getValue());
            }
//            httpPost.addHeader("Cookie","PHPSESSID=c892a6608a834f408292d7d572ca005259b8f2d25656b0.95111886; Hm_lvt_c8184fd80a083199b0e82cc431ab6740=1505293029,1506265901,1506396944; Hm_lpvt_c8184fd80a083199b0e82cc431ab6740=1506418061; _ga=GA1.2.1241460307.1505293029; _gid=GA1.2.302250075.1506396945");
//            httpPost.addHeader("Upgrade-Insecure-Requests", "1");
//            httpPost.addHeader("Content-Type","application/x-www-form-urlencoded");
//            httpPost.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
//            httpPost.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
//            httpPost.addHeader("Referer", "http://www.huangye88.com/search.html?kw=%E5%B9%BF%E5%91%8A&type=company");
            HttpResponse httpResponse = client.execute(httpPost);
            StatusLine statusLine = httpResponse.getStatusLine();

            if(HttpStatus.SC_OK  != statusLine.getStatusCode()) {
                return null;
            }
            //Header[] headers = httpResponse.getHeaders("Content-Type");
            HttpEntity entity = httpResponse.getEntity();
            String responseStr = EntityUtils.toString(entity, Charset.forName("UTF-8"));
            Document document = Jsoup.parse(responseStr);
            return document;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static JSONObject postForJson(String url, String requestBody, Map<String, String> headerMap) {
//    public static JSONObject postForJson(String url, Map<String, String> map, Map<String, String> headerMap) {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        try {
//            List<NameValuePair> params = new ArrayList<NameValuePair>();
//            httpPost.setEntity(new UrlEncodedFormEntity(params, Charset.forName("utf-8")));
//            for (Map.Entry<String, String> entry : map.entrySet()) {
//                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
//            }


            httpPost.setEntity(new StringEntity(requestBody));
            for (Map.Entry<String, String> header : headerMap.entrySet()) {
                httpPost.addHeader(header.getKey(), header.getValue());
            }
//            httpPost.addHeader("Cookie","PHPSESSID=c892a6608a834f408292d7d572ca005259b8f2d25656b0.95111886; Hm_lvt_c8184fd80a083199b0e82cc431ab6740=1505293029,1506265901,1506396944; Hm_lpvt_c8184fd80a083199b0e82cc431ab6740=1506418061; _ga=GA1.2.1241460307.1505293029; _gid=GA1.2.302250075.1506396945");
//            httpPost.addHeader("Upgrade-Insecure-Requests", "1");
//            httpPost.addHeader("Content-Type","application/x-www-form-urlencoded");
//            httpPost.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
//            httpPost.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
//            httpPost.addHeader("Referer", "http://www.huangye88.com/search.html?kw=%E5%B9%BF%E5%91%8A&type=company");
            HttpResponse httpResponse = client.execute(httpPost);
            StatusLine statusLine = httpResponse.getStatusLine();

            if(HttpStatus.SC_OK  != statusLine.getStatusCode()) {
                return null;
            }
            //Header[] headers = httpResponse.getHeaders("Content-Type");
            HttpEntity entity = httpResponse.getEntity();
            String responseStr = EntityUtils.toString(entity, Charset.forName("UTF-8"));
            System.out.println(responseStr);
            JSONObject jsonObject = JSON.parseObject(responseStr);
            return jsonObject;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Document getHtml(String url) {
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        try {
            httpGet.addHeader("Cookie", "PHPSESSID=c892a6608a834f408292d7d572ca005259b8f2d25656b0.95111886; Hm_lvt_c8184fd80a083199b0e82cc431ab6740=1505293029,1506265901; Hm_lpvt_c8184fd80a083199b0e82cc431ab6740=1506265901; _ga=GA1.2.1241460307.1505293029; _gid=GA1.2.1556649091.1506265901");
            httpGet.addHeader("Upgrade-Insecure-Requests", "1");
            httpGet.addHeader("Content-Type","application/x-www-form-urlencoded");
            httpGet.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
            httpGet.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
            HttpResponse httpResponse = client.execute(httpGet);
            StatusLine statusLine = httpResponse.getStatusLine();

            if(HttpStatus.SC_OK  != statusLine.getStatusCode()) {

            }
            //Header[] headers = httpResponse.getHeaders("Content-Type");
            HttpEntity entity = httpResponse.getEntity();
            String responseStr = EntityUtils.toString(entity, Charset.forName("UTF-8"));
            Document document = Jsoup.parse(responseStr);
            return document;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Document getHtml(String url, Map<String, String> headerMap) {
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        try {

            httpGet.setConfig(RequestConfig.custom().setConnectTimeout(50000).setSocketTimeout(50000).setConnectionRequestTimeout(50000).build());
            for(Map.Entry<String, String> entry : headerMap.entrySet()) {
                httpGet.addHeader(entry.getKey(), entry.getValue());
            }
            HttpResponse httpResponse = client.execute(httpGet);
            StatusLine statusLine = httpResponse.getStatusLine();

            if(HttpStatus.SC_OK  != statusLine.getStatusCode()) {

            }
            //Header[] headers = httpResponse.getHeaders("Content-Type");
            HttpEntity entity = httpResponse.getEntity();
            String responseStr = EntityUtils.toString(entity, Charset.forName("UTF-8"));
            Document document = Jsoup.parse(responseStr);
            return document;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static JSONObject getJson(String url) {
        String ip = RandomIp.getRandomIp();
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(RequestConfig.custom().setConnectionRequestTimeout(30000).setSocketTimeout(30000).setConnectTimeout(30000).build());
//        if(!ip.equals("")){
//            httpGet.addHeader("x-forwarded-for",ip);
//        }
        try {
            HttpResponse httpResponse = client.execute(httpGet);
            StatusLine statusLine = httpResponse.getStatusLine();

            if(HttpStatus.SC_OK  != statusLine.getStatusCode()) {
                throw new RuntimeException("返回状态不正确");
            }
            //Header[] headers = httpResponse.getHeaders("Content-Type");
            HttpEntity entity = httpResponse.getEntity();
            String responseStr = EntityUtils.toString(entity, Charset.forName("UTF-8"));
            JSONObject jsonObject = JSON.parseObject(responseStr);
            return jsonObject;
//            return document;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static JSONObject getJson(String url, Map<String, String> headerMap) {
        String ip = RandomIp.getRandomIp();
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(RequestConfig.custom().setConnectionRequestTimeout(30000).setSocketTimeout(30000).setConnectTimeout(30000).build());
//        if(!ip.equals("")){
//            httpGet.addHeader("x-forwarded-for",ip);
//        }
        try {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                httpGet.addHeader(entry.getKey(), entry.getValue());
            }

            HttpResponse httpResponse = client.execute(httpGet);
            StatusLine statusLine = httpResponse.getStatusLine();

            if(HttpStatus.SC_OK  != statusLine.getStatusCode()) {
                throw new RuntimeException("返回状态不正确");
            }
            //Header[] headers = httpResponse.getHeaders("Content-Type");
            HttpEntity entity = httpResponse.getEntity();
            String responseStr = EntityUtils.toString(entity, Charset.forName("UTF-8"));
            System.out.println(responseStr);
            JSONObject jsonObject = JSON.parseObject(responseStr);
            return jsonObject;
//            return document;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
